<template>
  <a-space mb-4>
    <a-button
      type="primary"
      @click="batchAddNew"
      :disabled="!selectRows.length"
    >
      生成新选项
    </a-button>

    <a-button type="primary" disabled v-if="!selectRows.length"
      >关联选项</a-button
    >
    <a-popconfirm
      title="关联选项"
      v-else
      @confirm="batchMergeConfirm"
      @cancel="merge_name = undefined"
    >
      <template #description>
        <a-select
          v-model:value="merge_name"
          w-250px
          placeholder="请选择"
          :getPopupContainer="el => el.parentNode"
          showSearch
          option-filter-prop="title"
        >
          <a-select-option
            v-for="item in tableCollection.rows"
            :key="item.option_name"
            :value="item.alias_name || item.option_name"
            :title="item.alias_name || item.option_name"
            >{{ item.alias_name || item.option_name }}</a-select-option
          >
        </a-select>
      </template>
      <a-button type="primary">关联选项</a-button>
    </a-popconfirm>
  </a-space>
  <a-table
    row-key="option_value"
    size="small"
    bordered
    :columns="columns"
    :data-source="currentActive.options"
    :pagination="false"
    :custom-row="customRow"
    :row-selection="{
      selectedRowKeys: selectKeys,
      onChange: (keys, rows) => {
        selectKeys = keys;
        selectRows = rows;
      },
    }"
    :scroll="{
      y: rowH - 150,
    }"
  >
    <template #bodyCell="{ column, record }">
      <span v-if="column.dataIndex == 'option_name'">
        <check-circle-filled
          v-if="isOptionUsed(currentActive, record as Option)"
          text-success
        />
        {{ record.option_name }}
      </span>
      <a-space v-if="column.dataIndex == 'action'">
        <a-popconfirm
          title="选择关联的选项"
          v-if="tableCollection.rows.length"
          @confirm="confirmMerge(currentActive, record as Option)"
          @cancel="currentSelect = []"
        >
          <template #description>
            <a-select
              w-250px
              :value="currentSelect"
              mode="multiple"
              placeholder="请选择"
              @change="value => (currentSelect = value as string[])"
              :getPopupContainer="el => el.parentNode"
              showSearch
              option-filter-prop="title"
            >
              <a-select-option
                :value="item.alias_name || item.option_name"
                :title="item.alias_name || item.option_name"
                v-for="item in tableCollection.rows"
                :key="item.option_name"
                :disabled="disableSelect(record as Option, item.alias_name)"
              >
                {{ item.alias_name || item.option_name }}
              </a-select-option>
            </a-select>
          </template>
          <a-button type="link" @click.stop>关联选项</a-button>
        </a-popconfirm>
        <a-button disabled v-else type="link">关联选项</a-button>
        <a-button
          type="link"
          @click="addNew(currentActive, record as Option)"
          :disabled="isDisabled(currentActive, record as Option)"
        >
          生成新选项
        </a-button>
      </a-space>
    </template>
  </a-table>
</template>

<script lang="tsx" setup>
import { useRowActive } from '../../useRowActive';
import { CheckCircleFilled } from '@ant-design/icons-vue';
import { TableColumnType } from 'ant-design-vue';
import { Match, Option } from '../../type';
import OptionTable, { getMatchKey, getOptionKey } from '../table';
import { Emitter } from 'mitt';

const props = defineProps<{
  tableCollection: OptionTable;
  rowH: number;
  currentActive: Match;
  mitt: Emitter<any>;
}>();

const { currentActive, mitt } = toRefs(props);

const columns: TableColumnType[] = [
  {
    title: '站点条件选项',
    dataIndex: 'option_name',
    ellipsis: true,
    sorter: (a, b) => useSorter(a.option_name, b.option_name),
  },
  {
    title: '图片',
    dataIndex: 'image_url',
    width: '100px',
    customRender: ({ value }) => {
      return <a-image src={value} class="h-50px w-full h-auto"></a-image>;
    },
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '220px',
    fixed: 'right',
  },
];

const currentSelect = ref<string[]>([]);
const selectKeys = ref<any[]>([]);
const selectRows = ref<Option[]>([]);
const addNew = (item: Match, record: Option) => {
  props.tableCollection.addNew({
    ...item,
    options: [{ ...record, ...omit(item, 'options') }],
  });
};

const batchAddNew = () => {
  selectRows.value.forEach(option => {
    props.tableCollection.addNew({
      ...currentActive.value,
      options: [{ ...option, ...omit(currentActive.value, 'options') }],
    });
  });
  selectKeys.value = [];
  selectRows.value = [];
};

const confirmMerge = (item: Match, row: Option) => {
  if (currentSelect.value.length) {
    currentSelect.value.forEach(select => {
      props.tableCollection.addMerge(select, {
        ...item,
        options: [{ ...row, ...omit(item, 'options') }],
      });
    });
    currentSelect.value = [];
  } else {
    return Promise.reject();
  }
};

const isOptionUsed = (matches: Match, record: Option) => {
  const { optionMap } = props.tableCollection.getMap;
  const optionKey = getOptionKey({
    ...record,
    category_name: matches.category_name,
    condition_name: matches.condition_name,
    website_code: matches.website_code,
    alias_name: record.option_name,
  });
  return optionMap.has(optionKey);
};
const isDisabled = (matches: Match, record: Option) => {
  const { conditionMap } = props.tableCollection.getMap;
  return isOptionUsed(matches, record) && conditionMap.has(record.option_name);
};

const disableSelect = (record: Option, option_name: string) => {
  const { conditionMap, matchMap } = props.tableCollection.getMap;
  const condition = conditionMap.get(option_name);
  if (condition) {
    const matchKey = getMatchKey({
      website_code: currentActive.value.website_code,
      category_name: currentActive.value.category_name,
      alias_name: option_name,
      condition_name: currentActive.value.condition_name,
    });
    const match = matchMap.get(matchKey);
    if (match) {
      return match.options.some(
        item =>
          item.option_name == record.option_name &&
          item.option_value == record.option_value &&
          match.website_code == currentActive.value.website_code &&
          match.condition_name == currentActive.value.condition_name &&
          match.category_name == currentActive.value.category_name &&
          match.category_path == currentActive.value.category_path
      );
    }
  }
  return false;
};

const merge_name = ref<string>();
const batchMergeConfirm = () => {
  if (!merge_name.value) {
    message.warn('请选择一个条件');
    return Promise.reject();
  }
  selectRows.value.forEach(select => {
    props.tableCollection.addMerge(merge_name.value!, {
      ...currentActive.value,
      options: [{ ...omit(select, 'options') }],
    });
  });
  selectKeys.value = [];
  selectRows.value = [];
  merge_name.value = undefined;
};

const customRow = useRowActive(active => {
  const row = currentActive.value.options[active];
  const { website_code, category_code, condition_name } = currentActive.value;
  const key = website_code + category_code + condition_name;
  if (row && isOptionUsed(currentActive.value, row)) {
    mitt.value.emit('changeRow', {
      key,
      row: { ...omit(currentActive.value, 'options'), ...row },
    });
  } else {
    mitt.value.emit('changeRow', { key });
  }
});
</script>
